<?php

namespace app\api\controller;

use app\admin\model\Project;
use app\admin\model\Projectexpert;
use app\common\controller\Api;
use think\Db;
use think\Env;

/**
 * 短信回执接口
 */
class Smsreceipt extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 阿里云短信回执处理示例
     *
     */
    public function index()
    {
        // 阿里云短信回执处理示例

        // 1. 获取原始POST数据
        $rawData = file_get_contents('php://input');
        // file_put_contents('sms_callback_error.log', $rawData . "\n", FILE_APPEND);
        $data = json_decode($rawData, true);
        // file_put_contents('sms_callback_error.log', json_encode($data). "\n", FILE_APPEND);
        // // 2. 验证签名（重要！防止伪造请求）
        // $signature = $data['signature'];
        // unset($data['signature']); // 签名参数不参与签名计算
        // $accessKeySecret = Env::get('sms.access_secret'); // 替换为你的AccessKey Secret

        // // 生成待签名字符串
        // ksort($data); // 按字典序排序参数
        // $canonicalizedQueryString = '';
        // foreach ($data as $key => $value) {
        //     $canonicalizedQueryString .= '&' . urlencode($key) . '=' . urlencode($value);
        // }
        // $stringToSign = 'POST&%2F&' . urlencode(substr($canonicalizedQueryString, 1));

        // // 计算签名
        // $sign = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));

        // // 验证签名是否匹配
        // if ($sign !== $signature) {
        //     file_put_contents('sms_callback_error.log', '签名验证失败: ' . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
        //     exit('签名验证失败');
        // }
        // file_put_contents('sms_callback_success.log', json_encode($data['SmsReportDetails']) . "\n", FILE_APPEND);
        // 3. 处理回执数据
        // foreach ($data['SmsReportDetails'] as $report) {
        //     $bizId = $report['biz_id'];       // 发送流水号
        //     $phone = $report['phone_number']; // 手机号
        //     $status = $report['success'];     // 是否成功（true/false）
        //     $errCode = $report['err_code'];  // 错误码
        //     $sendTime = $report['send_time']; // 发送时间
        //     $reportTime = $report['report_time']; // 回执时间

        //     // 这里编写你的业务逻辑：
        //     // - 更新数据库状态
        //     // - 记录日志
        //     // - 失败重发逻辑等
        // }

        foreach ($data as $report) {
            $sequenceId = $report['sequence_id']; // 序列号
            $phone = $report['phone_number']; //手机号
            $destCode = $report['dest_code']; //上行短信扩展号码，系统后台自动生成，不支持自定义传入。） 
            $sendTime = $report['send_time']; //运营商推送上行时间
            $content = $report['content']; //发送内容
            $lastRecord = Db::name('projectexpert')->where(['send_params_phone' => $phone])->order('createtime', 'desc')->find();
            if ($lastRecord['status'] == 1 && $lastRecord['sms_status'] == 2 && time() - $lastRecord['createtime'] <= Env::get('task.exec_time')) {
                Db::name('projectexpert')->where(['id' => $lastRecord['id']])->update(
                    [
                        'receipt_sequenceId' => $sequenceId,
                        'receipt_phone_number' => $phone,
                        'receipt_dest_code' => $destCode,
                        'receipt_send_time' => $sendTime,
                        'receipt_content' => $content,
                        'receipt_send_time' => time(),
                        'sms_status' => 4,
                        'status' => $content == 1 ? 2 : 3,
                        'receipt_time' => time()
                    ]
                );
                $pModel = new Project();
                $pModel->updateProjectStatus($lastRecord['project_id']);
            } else {
                Db::name('projectexpert')->where(['id' => $lastRecord['id']])->update(['sms_status' => 4, 'receipt_time' => time(), 'receipt_reason' => '数据状态不正确或者回复时间已过固定时间范围内']);
            }
        }
        // 4. 返回成功响应
        header('Content-Type: application/json');
        echo json_encode(["code" => 0, "msg" => "success"]);
    }

    /**
     * 处理2小时未回复的短信全部拒绝
     */
    public function dealNotReplied()
    {
        $exacTime = Env::get('task.exec_time'); //获取时间间隔(s)，即处理多久未回复数据
        Projectexpert::where('status', 1)->chunk(100, function ($models) use ($exacTime) {
            foreach ($models as $model) {
                if (time() - $model['createtime'] >= $exacTime) { //发送时间超过 多少秒的数据
                    Db::name('projectexpert')->where('id', $model['id'])->update(['status' => 3, 'updatetime' => time()]);
                    $this->updateBc();
                }
            }
        });
    }

    /**
     * 更新项目是否补抽
     */
    public function updateBc()
    {
        Project::where('status', 2)->chunk(100, function ($models) {
            foreach ($models as $model) {
                $dhfNum = Db::name('projectexpert')->where('project_id', $model['id'])->where('status', 1)->count();
                $ytyNum = Db::name('projectexpert')->where('project_id', $model['id'])->where('status', 2)->count();
                if ($dhfNum <= 0 && $ytyNum != $model['num']) {
                    $dhfNum = Db::name('project')->where('id', $model['id'])->update(['is_show_bc' => 2]);
                }
                if ($ytyNum >= $model['num']) {
                    Db::name('project')->where('id', $model['id'])->update(['status' => 3, 'agree_num' => $ytyNum]); //更新已同意数量 
                }
            }
        });
    }
}
